package slap.log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Date;

import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;

import slap.http.Header;
import slap.http.Request;
import slap.http.Response;
import slap.util.Time;

public class ACLogger {
	
	private static final org.slf4j.Logger SYS_LOG = LoggerFactory.getLogger("system");
	
	//112.123.93.131 - - [01/Jul/2011:09:24:05 +0800] "GET / HTTP/1.1" 200 4524 "-" "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"
	private static final String SYS_LOG_FORMAT = "{} - {} [{}] \"{}\" {} {} \"{}\" \"{}\"";
	
	
	public static void log(Request request, Response response, String contentLength){
		
		SYS_LOG.info(SYS_LOG_FORMAT, new Object[] {
				request.remoteAddress(), 
				"-", 
				Time.acFormatter.format(request.timeStamp),
				request.rawRequestString(),
				response.status,
				contentLength,
				safeGet(request, Header.Names.REFERER),
				safeGet(request, Header.Names.USER_AGENT)}
		);
	}
	
	private static String safeGet(Request request, String headerName){
		String value = "-";
		String header = request.header(headerName);
		if(header != null){
			value = header;
		}
		
		return value;
	}

}
